<?php

namespace app\api\controller;

use app\admin\model\User as UserModel;
use app\common\controller\ApiController;
use Firebase\JWT\JWT;
use Firebase\JWT\Key;
use think\cache\driver\Redis as CRedis;
use think\facade\Env;
use function app\api\json_decode;
use function app\api\request;
use function app\api\time;

class common extends ApiController
{
    public $user;
    public $openid;
    public $user_id;


    public function __construct(){

        parent::__construct();
        $this->needLogin();
    }

    public function needLogin()
    {

        if (empty($this->user)) {
            $this->getUser();
        }
        if (empty($this->user)) {
            $this->error('请先登录', '',401);
        }
    }


    public function getUser(){
        try {

            $token = request()->header('token');
            $host = request()->header('Host');
            if (!$token) {
                $this->error('请先登录'.$host, '',401);
            }
            $key = Env::get("JWT.key", "123456");
            $decode = JWT::decode($token, new Key($key, 'HS256'));
            if (!isset($decode->data->user_id)) {
                $this->error('请先登录'.$token, $decode,401);
            }

            if (isset($decode->exp) && $decode->exp<time()) {
                $this->error('登录已过期', $decode,401);
            }
            $new_token = $this->redis->get('token_' . $decode->data->user_id);
            if($new_token){
                $new_token=json_decode($new_token,true);
            }else{
                $new_token=[];
            }
            $ex=true;
            foreach ($new_token as $v){
                if($v["token"] == $token){
                    $ex=false;
                    break;
                }
            }
            if ($ex){
                $this->error('登录已过期'.$token, $decode,401);
            }
            $user_id = $decode->data->user_id;

            $m_user = new UserModel();
            $d_user = $m_user->find($user_id);

            if (!$d_user) {
                $this->error('请先登录', '',401);
            }

            $this->user=$d_user;
            $this->user_id=$user_id;
            $this->openid = $decode->data->openid;


        }catch (\Exception $e) {
            $this->error($e->getMessage(), '',401);
        }

    }

}